package bacasable;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;

public class MonAppli extends JFrame implements ActionListener {

    private JTable table;
    private JPopupMenu popupMenu = new JPopupMenu();
    private int selectedCol;
    private int selectedRow;

    public MonAppli() {
        build();
    }

    private void build() {
        String[][] rowData = {{"toto", "titi", "tutu"},
            {"bonjour", "aurevoir", "à bientot"}};
        String[] columnNames = {"COL 1", "COL 2", "COL 3"};
        table = new JTable(rowData, columnNames);
        table.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    showPopup(e);
                }
            }
        });
        getContentPane().add(table);
        JMenuItem menuItem = new JMenuItem("ACTION 1");
        menuItem.setActionCommand("ACTION1");
        menuItem.addActionListener(this);
        popupMenu.add(menuItem);
    }

    private void showPopup(MouseEvent e) {
        if (e.isPopupTrigger()) {
            Point p = new Point(e.getX(), e.getY());
            System.out.println(table.columnAtPoint(p));
            selectedCol = table.columnAtPoint(p);
            selectedRow = table.rowAtPoint(p);
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("La cellule du tableau concerné est : " + selectedCol + ";" + selectedRow);
    }

    /**
     * @param args
     */
    public static void main2(String[] args) {
        MonAppli appli = new MonAppli();
        appli.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        appli.pack();
        appli.setVisible(true);

    }
}